/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on Dec 11, 2009, 5:49:47 AM
 */

package server;


import Network.*;

import IO.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
//import javax.swing.*;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.DefaultListModel;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import javax.swing.event.ListDataListener;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.events.StartElement;

/**
 *
 * @author trang
 */
public class MainFrameServer extends BaseForm {


    protected NetworkServer server;

    //For timer
    public int counter;

    public ServerTimerTask task;
    public Timer timer;

    public class ServerTimerTask extends TimerTask
    {
        /**
         * duration of exam calculated by seconds
         */
        int duration;


        ServerTimerTask(int duration)
        {
            this.duration = duration;
        }

        public void run()
        {

            duration--;
            int hour = duration/3600;
            int minute = (duration - hour*3600) / 60;
            int second = duration - hour*3600 - minute*60;


            String timeString = String.valueOf(hour) +  ":" + String.valueOf(minute) + ":" +String.valueOf(second);

            if(duration == -1)
            {
                server.exam.stop = true;
                timer.cancel();

            }
            if(duration >= 0)
                lbTime.setText(timeString);
        }

    }


    /** Creates new form MainFrame */

    public MainFrameServer() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        StatusFrame = new javax.swing.JInternalFrame();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        lbUnsubmitted = new javax.swing.JLabel();
        lbSubmitted = new javax.swing.JLabel();
        lbNumClient = new javax.swing.JLabel();
        lbTime = new javax.swing.JLabel();
        lbStatus = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listQues = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        Questions = new javax.swing.JTextArea();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMenu4 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Server");

        StatusFrame.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        StatusFrame.setResizable(true);
        StatusFrame.setTitle("Status");
        StatusFrame.setName("Status  Frame"); // NOI18N
        StatusFrame.setVisible(true);

        jLabel1.setText("Number of clients has not finished the exam is: ");

        jLabel2.setText("Number of clients has finished the exam is: ");

        jLabel3.setText("Total number of clients :");

        jLabel4.setText("Time left :");

        lbUnsubmitted.setForeground(new java.awt.Color(255, 0, 0));
        lbUnsubmitted.setText("0");

        lbSubmitted.setForeground(new java.awt.Color(255, 0, 0));
        lbSubmitted.setText("0");

        lbNumClient.setForeground(new java.awt.Color(255, 0, 0));
        lbNumClient.setText("0");

        lbTime.setForeground(new java.awt.Color(255, 0, 0));
        lbTime.setText("0:00");

        javax.swing.GroupLayout StatusFrameLayout = new javax.swing.GroupLayout(StatusFrame.getContentPane());
        StatusFrame.getContentPane().setLayout(StatusFrameLayout);
        StatusFrameLayout.setHorizontalGroup(
            StatusFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(StatusFrameLayout.createSequentialGroup()
                .addGroup(StatusFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(StatusFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(StatusFrameLayout.createSequentialGroup()
                            .addComponent(jLabel4)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lbTime))
                        .addGroup(StatusFrameLayout.createSequentialGroup()
                            .addComponent(jLabel3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lbNumClient))
                        .addGroup(StatusFrameLayout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lbSubmitted))
                        .addGroup(StatusFrameLayout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addGap(18, 18, 18)
                            .addComponent(lbUnsubmitted)))
                    .addComponent(lbStatus))
                .addContainerGap(151, Short.MAX_VALUE))
        );
        StatusFrameLayout.setVerticalGroup(
            StatusFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(StatusFrameLayout.createSequentialGroup()
                .addGroup(StatusFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(lbUnsubmitted))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(StatusFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(lbSubmitted))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(StatusFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lbNumClient))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(StatusFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(lbTime))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lbStatus)
                .addContainerGap(47, Short.MAX_VALUE))
        );

        listQues.setModel(model);
        listQues.setSelectionModel(new DefaultListSelectionModel(){

            @Override
            public void setSelectionInterval(int arg0, int arg1) {

                Question q = server.exam.getQuestion(arg0);
                Questions.setText(q.toString());
                super.setSelectionInterval(arg0, arg1);
            }
        });
        jScrollPane1.setViewportView(listQues);

        Questions.setColumns(20);
        Questions.setEditable(false);
        Questions.setRows(5);
        jScrollPane2.setViewportView(Questions);

        jMenu1.setText("File");

        jMenuItem1.setText("Load exam");
        jMenuItem1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ClickLoadExam(evt);
            }
        });
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem2.setText("Exit");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Exam");
        jMenu2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu2ActionPerformed(evt);
            }
        });

        jMenuItem3.setText("Accept connecting");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem3);

        jMenuItem4.setText("Disconnect all");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem4);

        jMenuItem5.setText("Start the exam");
        jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem5ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem5);

        jMenuBar1.add(jMenu2);

        jMenu3.setText("Help");

        jMenu4.setText("About");
        jMenu4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu4MouseClicked(evt);
            }
        });
        jMenu3.add(jMenu4);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(StatusFrame)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(StatusFrame)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane1)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        try {
            // TODO add your handling code here:
//Load exam
     
         
          

            JFileChooser fc = new JFileChooser();
            //      {
            //      {
            int returnVal = fc.showOpenDialog(MainFrameServer.this);
            String filename = "";
            String path ="";
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                //This is where a real application would open the file.
                filename = file.getName();
                path = file.getAbsolutePath();
                 System.out.print(file.getAbsolutePath());
                System.out.print("Opening: " + file.getName());
            } else {
                System.out.print("Open command cancelled by user");
            }
            //     }
            
////Xoa gd
//            for(int i=0;i<listQues.getComponents().length;i++)
//            {
//                listQues.remove(i);
//                listQues.setVisible(true);
//            }
            Questions.setText("");
            validate();


            
            // Read file and write to temp file
            IOFIle.ReadAndWrite(path, "D:\\temp.xml");
             
            Exam xml = new Exam("D:\\temp.xml");
            // FOR TEST ONLY
            if(server == null)
            {
                server = new NetworkServer();
            }
            server.exam = xml;
            
                
            System.out.print("\n\n aa"+xml.getTitle());
            //load content of file to Application
              int numQuestion =xml.getTotalQuestion();
            
            DefaultListModel model = (DefaultListModel) listQues.getModel();
            String start = "a";
            for(int i=0;i<numQuestion;i++)
            {
                 model.add(i,"Question "+String.valueOf(xml.getQuestion(i).getNumber()));
                 Questions.append(String.valueOf(xml.getQuestion(i).getNumber())+")"+ xml.getQuestion(i).getStatement()+"\n");
                 int numChoice = xml.getQuestion(i).getNumberOfChoice();
               for(int k=0;k<numChoice;k++)
               {
                   Questions.append(xml.getQuestion(i).getOneChoice(k)+"\n");
               }
                 Questions.append("\n\n");
                 validate();
                 System.out.print("\n\n aa"+Integer.toString(i));
            }
            // add question detail to TextArea
        }
        catch (ParserConfigurationException ex)
        {
            Logger.getLogger(MainFrameServer.class.getName()).log(Level.SEVERE, null, ex);
        }


    }//GEN-LAST:event_jMenuItem1ActionPerformed

    public void setLabelStatus(String str)
    {
        lbStatus.setText(str);
    }

    private void jMenu4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu4MouseClicked
        // TODO add your handling code here:
        AboutUS a = new AboutUS();
        a.show();
    }//GEN-LAST:event_jMenu4MouseClicked

    public void refeshExam(int numClient, int numSubmit)
    {
        lbNumClient.setText(String.valueOf(numClient));
        lbSubmitted.setText(String.valueOf(numSubmit));

        int numUnsubmit = numClient - numSubmit;
        lbUnsubmitted.setText(String.valueOf(numUnsubmit));
    }

    public void refeshExamWhenSubmit()
    {
        int numClient = Integer.valueOf(lbNumClient.getText());
        int numSubmitted = Integer.valueOf(lbSubmitted.getText())+1;
        int numUnsubmit = numClient - numSubmitted;

        lbUnsubmitted.setText(String.valueOf(numUnsubmit));
        lbSubmitted.setText(String.valueOf(numSubmitted));
    }

    private void ClickLoadExam(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ClickLoadExam
        // TODO add your handling code here:
        JFileChooser fc = new JFileChooser ();

//        int i = fc.showDialog(this.getComponent(), null);
        File f = fc.getSelectedFile();

 //       FileDialog dia = new FileDialog(new Frame(),"loadFile",FileDialog.LOAD);
 //       dia.show();
        
 //      String file = dia.getFile();
        
    }//GEN-LAST:event_ClickLoadExam

    private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu2ActionPerformed
        // TODO add your handling code here:
//        server.allowConnect = false;
//        JOptionPane.showMessageDialog(new JDialog(), "Start the exam");
//        server.startExam();
    }//GEN-LAST:event_jMenu2ActionPerformed


    private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        server.allowConnect = false;
        //JOptionPane.showMessageDialog(new JDialog(), "Start the exam");
        lbStatus.setText("Start the exam");
        server.startExam();


        timer = new Timer();
        timer.schedule(new ServerTimerTask(1*Integer.parseInt(server.exam.getLength())), 0,1000);

        
    }                                          

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    
    /**
     * Disconnect all
     * @param evt
     */
    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
        // TODO add your handling code here:

        lbStatus.setText("Disconnect All");
        server.closeAllConnection();
        int currentConnect = server.getNumConnection();
        lbNumClient.setText(String.valueOf(currentConnect));
        lbUnsubmitted.setText("0");
        timer.cancel();
    }//GEN-LAST:event_jMenuItem4ActionPerformed


    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:

     //JDialog d = new DiaLogConnection();
     
     String str = JOptionPane.showInputDialog(new JDialog(), "Input port number here, plz");
     int port = Integer.valueOf(str);
//     server = new NetworkServer(port);
     if(server != null)
        server.serverAccept(port);
     else
         server = new NetworkServer(port);

     new serverListener(port, server,this);
//     server.exam.isActive = true;
//     server.exam.stop  = false;



     //d.show();

      //  MultipleChoiceExamServerApp.getApplication().show(d);
        
    }

    
    

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrameServer().setVisible(true);
          
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea Questions;
    private javax.swing.JInternalFrame StatusFrame;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lbNumClient;
    private javax.swing.JLabel lbStatus;
    private javax.swing.JLabel lbSubmitted;
    private javax.swing.JLabel lbTime;
    private javax.swing.JLabel lbUnsubmitted;
    private javax.swing.JList listQues;
    // End of variables declaration//GEN-END:variables
 public DefaultListModel model = new DefaultListModel();

 static public class serverListener extends Thread
 {
     NetworkServer server = null;
     MainFrameServer frameServer = null;
     int port ;
        public serverListener(int port, NetworkServer server, MainFrameServer frame) {
            this.port = port;
            this.server = server;
            this.frameServer = frame;
            start();
        }

        public void run()
        {
            frameServer.setLabelStatus("Accepting the connection with port: "+port);
            server.openConnection(port,frameServer);
        }


 }
}
